<template>
  <el-cascader
    v-if="show"
    expand-trigger="hover"
    filterable
    :options="options"
    :props="props"
    clearable
    @change="change"
  />
</template>

<script>
import {
  failureNotice
} from '@/util/common'
import {
  productDeviceNum,
  seriesDeviceNum
} from '@/api/iot/iotDeviceApi'
export default {
  name: 'CompanyProductSeriesCascade',
  props: {
    status: {
      type: Object,
      default: null
    },
    deptId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      show: true,
      productList: [],
      props: {
      },
      options: []
    }
  },
  watch: {
    status: {
      handler(val) {
        this.refresh()
      }
    },
    deptId: {
      handler(val) {
        this.refresh()
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      const that = this
      this.props = {
        checkStrictly: true,
        lazy: true,
        lazyLoad(node, resolve) {
          const { level, value } = node
          if (level === 0) {
            const req = {
              status: that.status,
              deptId: that.deptId
            }
            productDeviceNum(req).then(res => {
              const { code, data } = res
              if (code === '200') {
                const productList = []
                data.forEach(product => {
                  productList.push({
                    value: product.productId,
                    label: product.name,
                    leaf: false
                  })
                })
                const allProductItem = {}
                allProductItem.value = null
                allProductItem.label = that.$t('all')
                allProductItem.leaf = true
                productList.unshift(allProductItem)
                resolve(productList)
              } else if (code !== '201') {
                failureNotice(that)
              }
            })
          } else if (level === 1) {
            if (!value) {
              resolve([])
              return
            }
            const req = {
              productId: value,
              deptId: that.deptId
            }
            seriesDeviceNum(req).then(res => {
              const { code, data } = res
              if (code === '200') {
                const seriesList = []
                data.forEach(series => {
                  seriesList.push({
                    value: series.seriesId,
                    label: series.name,
                    leaf: true
                  })
                })
                resolve(seriesList)
              }
            })
          }
          resolve([])
        }
      }
    },
    refresh() {
      this.show = false
      this.$nextTick(() => {
        this.show = true
      })
    },
    change(data) {
      this.$emit('change', {
        productId: data[0],
        seriesId: data[1]
      })
    }
  }

}
</script>


